﻿using RabbitMQ.Client;
using System;
using System.Collections.Concurrent;
using System.Threading;

namespace Infrastructure.Utility.Core.RabbitMq
{
    public class ConnectionPool
    {
        private static ConnectionPool _connectionPool = null;
        private static readonly object AsyncLock = new object();

        public readonly ConnectionConfiguration Configuration;
        //空闲连接对象队列
        public readonly ConcurrentQueue<IConnection> FreeQueue;
        //使用中连接对象集合
        public readonly ConcurrentDictionary<IConnection, bool> BusyDic;
        //连接池使用率
        public readonly ConcurrentDictionary<IConnection, int> UseDic;
        //限制线程数，控制同时并发可用线程数
        public readonly Semaphore ConnectionPoolSemaphore;

        private ConnectionPool(ConnectionConfiguration configuration)
        {
            Configuration = configuration;
            FreeQueue = new ConcurrentQueue<IConnection>();
            BusyDic = new ConcurrentDictionary<IConnection, bool>();
            UseDic = new ConcurrentDictionary<IConnection, int>();

            ConnectionPoolSemaphore = new Semaphore(
                Configuration.MaxConnectionCount,
                Configuration.MaxConnectionUsingCount,
                Guid.NewGuid().ToString());
        }
        public static ConnectionPool Create(ConnectionConfiguration configuration)
        {
            if (_connectionPool == null)
            {
                lock (AsyncLock)
                {
                    if (_connectionPool == null)
                    {
                        _connectionPool = new ConnectionPool(configuration);
                    }
                }
            }
            return _connectionPool;
        }
    }
}
